import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  showSpinner: false
}) // 隐藏进度条


// 字符串转对象
function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    // console.log(route.component)
    if (route.component) {
      // 加粗文字 **
      if (route.component === 'LayOut') { //Layout组件特殊处理
        route.component = () =>
          import('@/views/base/LayOut/index.vue')
      } else {
        // console.log(route.component)
        let url = route.component
        route.component = () =>
          import(`@/views${url}`)
      }
    }
    if (route.children) {
      route.children = filterAsyncRouter(route.children)

    }
    return true
  })
  return accessedRouters
}

let GetRouter = sessionStorage.getItem("RouterList")
let accessedRouters = ''
// console.log(GetRouter)
if (GetRouter !== null) {
  GetRouter = JSON.parse(GetRouter)
  accessedRouters = filterAsyncRouter(GetRouter)
  router.addRoutes(accessedRouters)
  router.options.routes = accessedRouters
}

let flag = 0

router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title
  let GetRouterList = sessionStorage.getItem("RouterList")
  if (GetRouterList !== null && flag === 1) {
    GetRouterList = JSON.parse(GetRouterList)
    accessedRouters = filterAsyncRouter(GetRouterList)
    router.addRoutes(accessedRouters)
    router.options.routes = accessedRouters
    next()
  } else {
    next()
  }
  flag++

});

router.afterEach(() => {
  NProgress.done();
});